import { fetchLoginUser, login, logout } from '@/services/login';
import { history } from 'umi';
import { getPageQuery } from '@/utils/utils';


export default {
  namespace: 'login',
  state: {
    loginStatus: null,
    loginUser: null,
  },
  effects: {
    *login({ payload }, { call, put }) {
      const response = yield call(login, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      if (response.success) {
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        if (redirect) {
          const redirectUrlParams = new URL(redirect);
          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            if (window.routerBase !== '/') {
              redirect = redirect.replace(window.routerBase, '/');
            }
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = '/';
            return;
          }
        }
        history.replace(redirect || '/');
      }
    },

    *logout(_, { call, put }) {
      yield put({ type: 'clearUserData' });
      yield call(logout);
    },

    *fetchLoginUser(_, { call, put }) {
      const response = yield call(fetchLoginUser);
      if (response.success) {
        yield put({
          type: 'saveLoginUser',
          payload: response.data,
        });
      }
    },
  },
  reducers: {
    changeLoginStatus(state, { payload }) {
      return { ...state, loginStatus: payload };
    },

    saveLoginUser(state, { payload }) {
      return { ...state, loginUser: payload };
    },

    clearUserData() {
      return {};
    },

    sessionTimeout(state, { payload: { sessionTimeout } }) {
      if (!state.loginUser) {
        return state;
      }
      return { ...state, loginUser: { ...state.loginUser, sessionTimeout } };
    },
  },
};
